--------------------------------------------------------------------------------
---  @Project:   KappaFramework
---  @FileName:  server.lua
---  @Author:    xxx_xxx@xxx.co.jp
---  @Brief:     
---  @Date:
--------------------------------------------------------------------------------

require"util"
using"socket"
using"copas"

Service = function(App)
  --Attach the Apps filter to the server's handler function
  Handler   = function(skt)
    App.Continue = true
    while App.Continue==true do
      local data = receive(skt)
      if (data==nil)then
        -->continue
        break
      else
        App.Continue = App.Filter(data) -->We attach the filter here
        send(skt, "ok\r\n")
      end  
    end
  end
  
  App.hndServer = assert(socket.bind(App.IP,App.PORT))-->create a new server
  if App.hndServer then
    addserver(App.hndServer, Handler)
    logMsg("Create service, success:"..App.Name)
  else
    return logMsg("Create service, failure:"..App.Name)
  end
  logMsg("Connected Service:"..App.Name..";"..App.IP..";"..App.PORT)
  App.Continue = true  
  while App.Continue do 
    step(App.FREQUENCY) --loop every X seconds
  end
  return logMsg("Terminated Service:"..App.Name..";"..App.IP..";"..App.PORT)
end

--- Demo Structure -------------------------------------------------------------
-- This is what a sample service object looks like
MyApp = {
  Name      = "demo",
  hndServer = nil, -->The service will assign a handler here
  IP        = "localhost",
  PORT      = 666,
  FREQUENCY = 1, -->seconds
  Filter    = function(data) -->all incomming data will pass through this filter
    if (data == "shutdown") then
      return false
    else
      print(data) 
      return true
    end
  end,
}
--------------------------------------------------------------------------------

--- Usage ----------------------------------------------------------------------
--  Service(MyApp)
--------------------------------------------------------------------------------























--------------------------------------------------------------------------------
--  EOF
--------------------------------------------------------------------------------
